package com.example.sid.ui.fragments.app_token

import android.widget.Button
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import com.example.sid.R
import com.example.sid.data.ValueRamStorage
import com.example.sid.how_to_use.AsyncSIDFacade
import kotlinx.coroutines.launch
import sberid.sdk.auth.pkce.PkceUtils
import java.security.SecureRandom

/**
 * Тут можно будет обновить апптокен, если он устарел
 */
class UpdateAppTokenFragment : Fragment(R.layout.fragment_update_app_token) {

	private val checkAppTokenButton: Button?
		get() = view?.findViewById(R.id.check_app_token)

	private val updateAppTokenButton: Button?
		get() = view?.findViewById(R.id.update_app_token)

	private val infoTextView: TextView?
		get() = view?.findViewById(R.id.info_text_view)

	override fun onStart() {
		super.onStart()

		lifecycleScope.launch {
			AsyncSIDFacade.subscribeToAppTokenEvents(viewLifecycleOwner) {
				infoTextView?.text = it.toString()
			}
		}

		checkAppTokenButton?.setOnClickListener {
			lifecycleScope.launch {
				AsyncSIDFacade.checkAppTokenForValid()
			}
		}

		updateAppTokenButton?.setOnClickListener {
			lifecycleScope.launch {
				val codeVerifide = PkceUtils.generateRandomCodeVerifier(SecureRandom())
				val codeChallenge = PkceUtils.deriveCodeVerifierChallenge(codeVerifide)

				lifecycleScope.launch {
					AsyncSIDFacade.updateAppToken(
						clientId = ValueRamStorage.partnerID,
						scope = ValueRamStorage.partnerScope,
						redirectUri = ValueRamStorage.partnerUrlRedirect,
						state = ValueRamStorage.partnerState,
						nonce = ValueRamStorage.partnerNonce,
						codeChallenge = codeChallenge,
						codeChallengeMethod = PkceUtils.getCodeChallengeMethod()
					)
				}
			}
		}
	}

}